<template>
	<section>
		<el-row>
			<ButtonTable :data="buttons" v-on:edit="edit" v-on:update="update" v-on:remove="removeButton"></ButtonTable>
		</el-row>
		<el-row v-if="editBtn">
			<ButtonEdit :sourceBtn="editBtn" v-on:cancel="editBtn=undefined" v-on:submit="editButton"></ButtonEdit>
		</el-row>
	</section>
</template>

<script>
	import ButtonTable from './ButtonTable.vue';
	import ButtonEdit from './ButtonEdit.vue';
	import WxButton from './WxButton.vue';
	export default {
		name:'menus-management',
		components:{
			ButtonEdit,
			WxButton,ButtonTable
		},
		data(){
			return {
				buttons:[],

				editBtn:undefined,
			}
		},

		mounted(){
			this.initialize();
		},
		methods:{
			initialize(){
				this.request()
			},
			clean(obj){
				for(let propName in obj) {
					if(obj[propName] === null || obj[propName] === undefined) {
						delete obj[propName];
					}
				}
			},
			update(data){
				this.$store.dispatch({type:'updateWechatMenu',data})
					.then(res=>{
						this.$message({type:'success',message:'保存成功'});
						this.request();
					})
					.catch(error=>{
						this.$message({type:'error',message:'保存数据不成功'});
						this.request();
					});
			},
			request(){
				this.$store.dispatch({type:'getWechatMenu'})
					.then(res=>{
						if(!res.errCode){
							res.buttons.map(btn=>this.clean(btn));
							this.buttons = res.buttons;
						}else{
							this.$message({type:'error',message:err.message});
						}
					})
					.catch(error=>this.$message({type:'error',message:error}));
			},
			edit(button){
				this.rootIndex = this.buttons.indexOf(button);
				if(!button.type) button.type = '';
				this.editBtn = undefined;
				setTimeout(()=>{
					this.editBtn = button;
				},50);
			},
			removeButton(button){
				this.editBtn = undefined;
				this.rootIndex = this.buttons.indexOf(button);
				this.$confirm('确定删除目录?').then(res=>{
					this.buttons.splice(this.rootIndex,1);
					this.update({buttons:this.buttons});
				}).catch(()=>{})
			},
			editButton(button){
				this.buttons[this.rootIndex] = button;
				this.update({buttons:this.buttons});
				this.editBtn = undefined;
			},
		}
	}
</script>

<style lang="scss"></style>
